import Konva from 'konva';
import * as rx from 'rxjs';
import { BaseResponse } from '../api';
import { correctSaveImage } from '../api/editor/upload';
import { ImageManageInfo } from '../hooks/image';

// /**
//  *
//  * @param workerId
//  * @returns
//  */
// export const iniHomeWorkPrepareData=(workerId:WorkID)=>{
//     return  rx.from(getPrepareLessons(workerId)).pipe(rx.tap(val=>console.log(val)))
// }
/**
 ** ImageManageInfo ***** ImageManageInfo ***** ImageManageInfo ***** ImageManageInfo ...
 ** ImageToolManage  im ***** im ***** im ***** im  ...
 ** Promise  correctSaveImage ***** correctSaveImage ***** correctSaveImage ***** correctSaveImage ...
 ** BaseResponse ***** BaseResponse ***** BaseResponse ***** BaseResponse ...
 *******boolen*****
 * 上传流水线
 * @param imageManages
 * @param callBack
 * @returns
 */
export const saveLogic = (imageManages: ImageManageInfo[], callBack: (url: string, count: number) => void, failCallBack: (url: string) => void) => {
  const successLogic = (res: BaseResponse<string>, idx: number) => {
    return rx.of(res).pipe(
      rx.tap((r) => {
        callBack(res.data, idx);
      })
    );
  };
  const fileLogic = (res: BaseResponse<string>) => {
    return rx.of(res).pipe(
      rx.tap((r) => {
        failCallBack(res.msg!);
      })
    );
  };
  return rx.from(imageManages).pipe(
    rx.map((node) => node.im),
    rx.mergeMap((im) => {
      const bgs = im.stage.find('.bgImage');
      return rx.iif(
        () => bgs.length > 0,
        (() => {
          const bg = bgs[0];
          // const scale = bg.scale();
          // if (typeof scale.x === 'number' && typeof scale.y === 'number') {
          //   im.layers.forEach((n) => {
          //     n.scale({ x: 2 - scale.x, y: 2 - scale.y });
          //   });
          // }
          // bg.scaleX(1);
          // bg.scaleY(1);
          let uploadInfo = im.stage.getClientRect();
          // const bgcolor=new Konva.Rect({...im.stage.getClientRect(),fill:'white'});
          // bgcolor.zIndex(-1);
          // im.bgLayer.add(bgcolor);
          const data = im.stage.toDataURL({
            mimeType: 'image/jpeg',
            x: uploadInfo.x,
            y: uploadInfo.y,
            width: uploadInfo.width,
            height: uploadInfo.height,
            quality: 1
          });
          const pos = im.state.baseUrl.lastIndexOf('/');
          return rx.from(
            correctSaveImage({
              file_name: im.state.baseUrl.substring(pos + 1),
              file_content: data
            })
          );
        })(),
        rx.EMPTY
      );
    }),
    rx.switchMap((rs, idx) => {
      return rx.iif(() => rs.code === 0, successLogic(rs, idx), fileLogic(rs));
    }),
    /** */
    rx.every((rs) => rs.code === 0)
  );
};
